<template>
  <div>
    <el-row>
      <el-form :inline="true" :model="search" class="demo-form-inline">
        <el-col :span="6">
          <el-form-item label="人员姓名">
            <el-input v-model="search.name" placeholder="人员姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="账号">
            <el-input v-model="search.account" placeholder="账号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="角色">
            <el-select v-model="search.roleId" placeholder="角色">
              <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态">
            <el-select v-model="search.status" placeholder="状态">
              <el-option label="启用" value="enable"></el-option>
              <el-option label="禁用" value="disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <el-button type="success" @click="fetchData">查询</el-button>
    <el-button type="primary" @click="openDialog('add')">新增</el-button>
    <el-table :data="users" style="width: 100%">
      <el-table-column prop="scope.$index + 1" type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="name" label="人员姓名"></el-table-column>
      <el-table-column prop="account" label="账号"></el-table-column>
      <el-table-column prop="roleName" label="角色"></el-table-column>
      <el-table-column prop="sratus" label="状态">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status == 'enable'"
            @change="(value) => handleSwitchChange(scope.row, value)"
          ></el-switch>
          <el-popconfirm
            v-if="pendingRole && pendingRole.roleId === scope.row.roleId"
            :title="`确定要${scope.row.status === 'enable' ? '禁用' : '启用'}这个角色吗？`"
            @confirm="confirmToggleStatus"
            @cancel="cancelToggleStatus"
            ref="popconfirmRef"
            :key="scope.row.roleId"
          >
            <template slot="reference">
              <el-button
                type="text"
                style="padding:0;margin-left:10px;"
              >{{ scope.row.status === 'enable' ? '禁用' : '启用' }}</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button-group>
            <el-button type="primary" size="mini" @click="openDialog('edit', scope.row)">修改</el-button>
            <el-button
              type="warning"
              size="mini"
              @click="toggleStatusConfirm(scope.row)"
            >{{ scope.row.status === 'enable' ? '禁用' : '启用' }}</el-button>
            <el-button type="danger" size="mini" @click="deleteUser(scope.row)">删除</el-button>
            <el-button type="info" size="mini" @click="resetPassword(scope.row)">重置密码</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="users.length > 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form">
        <el-form-item label="账号" :disabled="dialogType === 'edit'">
          <el-input v-model="form.account"></el-input>
        </el-form-item>
        <el-form-item label="人员姓名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" v-if="dialogType === 'add'">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" v-if="dialogType === 'add'">
          <el-input type="password" v-model="form.confirmPassword"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.roleId" style="width: 100%">
            <el-option label="房源发布员" :value="1"></el-option>
            <el-option label="资格审核员" :value="2"></el-option>
            <el-option label="系统管理员" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
  
  <script>
export default {
  data() {
    return {
      search: {
        name: "",
        account: "",
        roleId: "",
        status: ""
      },
      users: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      dialogTitle: "",
      dialogType: "",
      form: {
        account: "",
        name: "",
        password: "",
        confirmPassword: "",
        roleId: "",
        status: "enable"
      },
      pendingRole: null,
      pendingValue: null,
      roles: []
    };
  },
  methods: {
    fetchRoles() {
      this.$axios.get("/roles").then(response => {
        this.roles = response.data.data;
      });
    },
    fetchData() {
      let curr =
        this.search.name == "" ? (this.currentPage - 1) * this.pageSize : 0;
      this.$axios
        .post("/admin/get", {
          size: this.pageSize,
          curr,
          ...this.search
        })
        .then(res => {
          this.users = res.data.data;
          this.total = res.data.total;
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    openDialog(type, user = {}) {
      this.dialogType = type;
      this.dialogTitle = type === "add" ? "新增人员" : "修改人员信息";
      if (type === "edit") {
        this.form = { ...user, password: "", confirmPassword: "" };
      } else {
        this.form = {
          account: "",
          name: "",
          password: "",
          confirmPassword: "",
          role: "",
          status: "enabled"
        };
      }
      this.dialogVisible = true;
    },
    submitForm() {
      let url;
      if (this.dialogType === "add") url = "admin/add";
      else url = "admin/update";
      this.$axios
        .post(url, this.form)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
          this.dialogVisible = false;
          this.fetchData();
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    toggleStatusConfirm(user) {
      this.$confirm("确定要修改该用户的状态吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.toggleStatus(user);
        })
        .catch(() => {});
    },
    toggleStatus(user) {
      this.$axios
        .post("/admin/set", {
          id: user.id,
          name: user.name,
          status: user.status === "enable" ? "disabled" : "enable"
        })
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
          this.fetchData();
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    deleteUser(user) {
      this.$confirm("确定要删除该用户吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.$axios
            .post("/admin/delete", { id: user.id, name: user.name })
            .then(res => {
              if (res.data.code === 200) {
                this.$message.success(res.data.message);
              } else {
                this.$message.error(res.data.message);
              }
              this.fetchData();
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    },
    resetPassword(user) {
      this.$axios
        .post("/admin/reset", { id: user.id, name: user.name })
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
          this.fetchData();
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchData();
    },
    handleSwitchChange(role, value) {
      this.pendingRole = role;
      this.pendingValue = value;
      this.$nextTick(() => {
        if (this.$refs.popconfirmRef) {
          this.$refs.popconfirmRef.showPopper = true;
        }
      });
    },
    confirmToggleStatus() {
      if (this.pendingRole) {
        this.pendingRole.status = this.pendingValue ? "disabled" : "enable";
        this.toggleStatus(this.pendingRole);
        this.pendingRole = null;
        this.pendingValue = null;
      }
    },
    cancelToggleStatus() {
      this.pendingRole = null;
      this.pendingValue = null;
    }
  },
  mounted() {
    this.fetchData();
    this.fetchRoles();
  }
};
</script>
  